package com.yuanfengPlus.utils;

import com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper;
import com.yuanfengPlus.basicInfoManage.loginfo.model.LogInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

import org.springframework.stereotype.Component;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;


import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

@Aspect
@Component
public class LoggingAspect {

    @javax.annotation.Resource
    private ILogInfoMapper ilim;

    private Properties logMappingProperties;

    public LoggingAspect() {
        try {
            Resource resource = new ClassPathResource("log-mapping.properties");
            logMappingProperties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Before("execution(* com.yuanfengPlus..*(..)) && !within(com.yuanfengPlus.utils..*)" +
            "&& !within(com.yuanfengPlus.config..*) && !within(com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper)" +
            "&& !execution(* com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper.insert(..))" +
            "&& !execution(* com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper.updateResult(..))")
    public void logBefore(JoinPoint joinPoint) {
        LogInfo log = new LogInfo();
        log.setTimestamp(new Date());
        log.setLevel("INFO");
        log.setClassName(convertToBusinessTerm(joinPoint.getTarget().getClass().getName()));
        log.setMethodName(convertToBusinessTerm(joinPoint.getSignature().getName()));
        log.setParameters(Arrays.toString(joinPoint.getArgs()));
        ilim.insert(log);
    }

    @AfterReturning(pointcut = "execution(* com.yuanfengPlus..*(..)) && !within(com.yuanfengPlus.utils..*)" +
            "&& !within(com.yuanfengPlus.config..*) && !within(com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper)" +
            "&& !execution(* com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper.insert(..))" +
            "&& !execution(* com.yuanfengPlus.basicInfoManage.loginfo.dao.ILogInfoMapper.updateResult(..))", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        LogInfo log = findLatestLog(joinPoint);
        if (log != null) {
            log.setResult(result.toString());
            ilim.updateResult(log.getId(), log.getResult());
        }
    }

    private LogInfo findLatestLog(JoinPoint joinPoint) {
        // 实现查找最新日志记录的逻辑
        return null;
    }

    private String convertToBusinessTerm(String original) {
        return logMappingProperties.getProperty(original, original);
    }
}

